import {
  getIceServers,
  handleCall,
  createOffer,
  setAnswer,
  handleCloseCall,
  addIceCandidate,
  getIceCandidate,
} from '../services/webrtc-socket-service.js'

export const handleGetIceServersRequest = async (ctx) => {
  try {
    const { browserName, browserVersion, osName } = ctx.query
    console.log('\x1b[32m%s\x1b[0m', `osName: ${osName}`, );
    console.log('\x1b[32m%s\x1b[0m', `browserName: ${browserName} ${browserVersion}`);
    ctx.body = await getIceServers()
    console.log('Get the ICE server configuration')
  } catch (error) {
    console.error('Error getting ICE server configuration:', error)
  }
}
export const handleCallRequest = async (ctx) => {
  try {
    const peerId = ctx.query.peerid
    const url = ctx.url
    const offer = ctx.request.body

    ctx.body = await handleCall(peerId, url, offer)
    console.log('Send offer and get answer')
  } catch (error) {
    console.error('Error sending offer and getting answer:', error)
  }
}
export const handleCreateOfferRequest = async (ctx) => {
  try {
    const peerId = ctx.query.peerid
    const url = ctx.url

    ctx.body = await createOffer(peerId, url)
    console.log('Create an offer')
  } catch (error) {
    console.error('Error creating offer:', error)
  }
}
export const handleSetAnswerRequest = async (ctx) => {
  try {
    const peerId = ctx.query.peerid
    const url = ctx.url
    const answer = ctx.request.body

    ctx.body = await setAnswer(peerId, url, answer)
    console.log('Set an answer')
  } catch (error) {
    console.error('Error setting answer:', error)
  }
}
export const handleHangupRequest = async (ctx) => {
  try {
    ctx.body = await handleCloseCall(ctx.url)
    console.log('Close the call')
  } catch (error) {
    console.error('Error closing call:', error)
  }
}
export const handleAddIceCandidateRequest = async (ctx) => {
  try {
    const url = ctx.url
    const candidate = ctx.request.body

    ctx.body = await addIceCandidate(url, candidate)
    console.log('Add ICE candidates')
  } catch (error) {
    console.error('Error adding ICE candidate:', error)
  }
}
export const handleGetIceCandidateRequest = async (ctx) => {
  try {
    const peerId = ctx.query.peerid
    const url = ctx.url

    ctx.body = await getIceCandidate(peerId, url)
    console.log('Get a list of ICE candidates')
  } catch (error) {
    console.error('Error getting ICE candidates:', error)
  }
}
export const handleHelpRequest = async (ctx) => {
  ctx.body = `
    Available API endpoints:
    - GET  /api/getIceServers : Get ICE Servers configuration
    - POST /api/call          : Send offer and get answer
    - POST /api/createOffer   : Create an offer
    - POST /api/setAnswer     : Set an answer
    - POST /api/hangup        : Close a call
    - POST /api/addIceCandidate : Add an ICE candidate
    - GET  /api/getIceCandidate : Get the list of ICE candidates
    - GET  /api/help          : Get the list of available API endpoints
  `
}
